package com.ice.work.project.smart.doc.builder;

import com.google.common.collect.Lists;
import com.ice.work.project.smart.doc.constant.DocGlobalConstant;
import com.ice.work.project.smart.doc.model.ApiDoc;
import com.ice.work.project.smart.doc.model.ApiMethod;
import com.thoughtworks.qdox.model.JavaAnnotation;
import com.thoughtworks.qdox.model.JavaClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 生成文档的抽象类  抽取 流程方法
 * @Author DELL
 * @Create 2019-12-31
 * @Since 1.0.0
 */
@Slf4j
public abstract class AbstractBuildDoc {

    /**
     * 1 加载 java 文件
     * 2 反射 java 文件
     */
    public void execute() {
        Map<String, JavaClass> javaClassMap = loadJavaFile();
        List<ApiDoc> apiDocs = getApiDoc(javaClassMap);
    }

    /**
     * 加载java文件
     *
     * @return
     */
    public abstract Map<String, JavaClass> loadJavaFile();

    public List<ApiDoc> getApiDoc(Map<String, JavaClass> javaClassMap) {
        final List<ApiDoc> apiDocs = Lists.newArrayList();
        if (MapUtils.isEmpty(javaClassMap)) {
            return apiDocs;
        }
        javaClassMap.forEach((k, cls) -> {
            if (checkController(cls)) {
                log.debug("处理类:{}", k);
                String controllerName = cls.getName();
                List<ApiMethod> apiMethodDocs = getApiMethods(cls);
                ApiDoc apiDoc = new ApiDoc();
                apiDoc.setList(apiMethodDocs);
                apiDoc.setName(controllerName);
                apiDocs.add(apiDoc);
            }
        });
        return apiDocs;
    }

    /**
     * 判断是不是controller类
     *
     * @param cls
     * @return
     */
    private boolean checkController(JavaClass cls) {
        if (Objects.isNull(cls)) {
            return false;
        }
        List<JavaAnnotation> classAnnotations = cls.getAnnotations();
        if (CollectionUtils.isEmpty(classAnnotations)) {
            return false;
        }
        for (JavaAnnotation annotation : classAnnotations) {
            String annotationName = annotation.getType().getName();
            boolean isController = DocGlobalConstant.SHORT_CONTROLLER.equals(annotationName)
                    || DocGlobalConstant.SHORT_REST_CONTROLLER.equals(annotationName)
                    || DocGlobalConstant.REST_CONTROLLER_FULLY.equals(annotationName)
                    || DocGlobalConstant.CONTROLLER_FULLY.equals(annotationName);
            if (isController) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取 api 请求方法
     *
     * @param javaClass
     * @return
     */
    private List<ApiMethod> getApiMethods(JavaClass javaClass) {
        List<ApiMethod> apiMethods = Lists.newArrayList();
        return apiMethods;
    }
}
